package com.yyjj.yyjj.payment.controller;

import com.yyjj.yyjj.common.result.Result;
import com.yyjj.yyjj.common.result.ResultCodeEnum;
import com.yyjj.yyjj.enums.PaymentType;
import com.yyjj.yyjj.payment.service.PaymentInfoService;
import com.yyjj.yyjj.payment.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 * 微信支付 API
 * </p>
 */
@Api(tags = "微信支付接口")
@RestController
@RequestMapping("/api/payment/weixin")
@RequiredArgsConstructor
public class WeixinController {

    @Autowired
    private WeixinService weixinPayService;

    @Autowired
    private PaymentInfoService paymentService;

    //调用微信支付系统生成预付单
    @ApiOperation(value = "下单 小程序支付")
    @GetMapping("/createJsapi/{orderNo}")
    public Result createJsapi(@PathVariable("orderNo") String orderNo){
        Map<String,String> map= weixinPayService.createJsapi(orderNo);
        return Result.ok(map);
    }

    //查询订单支付状态
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable("orderNo") String orderNo){
        //调用查询接口
        Map<String, String> resultMap = weixinPayService.queryPayStatus(orderNo);
        if (resultMap == null) {//出错
            return Result.build(null, ResultCodeEnum.valueOf("支付失败"));
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))) {//如果成功
            //更改订单状态，处理支付结果
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no,resultMap);
            return Result.ok(null);
        }
        return Result.build(null, ResultCodeEnum.valueOf("支付中"));
    }



}
